//
//  ViewController.m
//  btReaderTest
//
//  Created by Chenfan on 3/19/15.
//  Copyright (c) 2015 Chenfan. All rights reserved.
//

#import "ViewController.h"
#import "SRIDCardReader/SRIDCardReader.h"


static NSString *const kCharacteristicUUID = @"CCE62C0F-1098-4CD0-ADFA-C8FC7EA2EE90";

static NSString *const kServiceUUID = @"50BD367B-6B17-4E81-B6E9-F62016F26E7B";

extern     NSMutableData *_readData;
@interface ViewController ()<SRIDCardReaderDelegate,CBCentralManagerDelegate,CBPeripheralDelegate,NSXMLParserDelegate>{
    BOOL stop;
    NSString *ip;
    int port;
    NSArray *segmentedArray;
    int rowCount;
    NSMutableArray *deviceList;
    ZSYPopoverListView *listView;
    SRIDCardReader* idManager;
    double recrodTime;
    UIAlertView *customAlertView;
    NSString *currentIP;
    int currentPort;
    CBCentralManager *manager;
    
    NSMutableArray *devArray;
    
    NSMutableDictionary *certInfo;
    
    NSString *certInfoKey;
    
    NSObject *currentDevice;
    
    
}
@property (nonatomic, retain) NSIndexPath *selectedIndexPath;

@property(strong,nonatomic)CBCentralManager *centralManager;

@property(strong,nonatomic)NSMutableData *mutableData;

@property(strong,nonatomic)CBPeripheral *peripheral;
@end

@implementation ViewController
@synthesize selectedIndexPath = _selectedIndexPath;

- (void)viewDidLoad {
    [super viewDidLoad];
    //身份证信息清零
    name.text=@"";
    sex.text=@"";
    mz.text=@"";
    year.text=@"";
    mon.text=@"";
    day.text=@"";
    addr.text=@"";
    idNo.text=@"";
    org.text=@"";
    expDate.text=@"";
    // Do any additional setup after loading the view, typically from a nib.
    
//初始化阅读器对象
    idManager=[SRIDCardReader instanceWithManagerIP:@"id.esaleb.com" port:6100 account:@"test01" password:@"12315aA..1" key:@"FE870B0163113409C134283661490AEF"];
//    idManager=[SRIDCardReader instanceWithManagerIP:nil port:6100 account:@"test01" password:@"12315aA..1" key:@"FE870B0163113409C134283661490AEF"];

    idManager.delegate=self;
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docPath = [paths objectAtIndex:0];
    NSString *myFile = [docPath stringByAppendingPathComponent:@"my.ip"];
    //读取IP
    currentIP = [[NSString alloc] initWithContentsOfFile:myFile];
    if(currentIP==nil){
        currentIP=@"114.119.32.11";
        [currentIP writeToURL:myFile atomically:YES];
    }
    
    myFile = [docPath stringByAppendingPathComponent:@"my.port"];
    //读取文件
    NSString *portStr = [[NSString alloc] initWithContentsOfFile:myFile];
    if(portStr==nil){
        portStr=@"6000";
        [portStr writeToURL:myFile atomically:YES];
        currentPort=6000;
    }else{
        currentPort=[portStr intValue];
    }
    
//    currentIP=@"124.160.71.76";
//    currentPort=6000;
    [idManager setServerIP:currentIP andPort:currentPort];
    
//    [idManager setServerIp:currentIP andPort:currentPort serVerSndIp:@"234.34.43.1" andPortSnd:633];

    
    listView = [[ZSYPopoverListView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
    listView.titleName.text = @"阅读器列表";
    listView.datasource = self;
    listView.delegate = self;
    
    dn.lineBreakMode=UILineBreakModeCharacterWrap;
    dn.numberOfLines=0;
    
    manager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
}

//将当前时间格式化成yyyyMMddHHmmss
- (NSString *)getNowTime{
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"HH:mm:ss:SSS"];
    //获取系统当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    return currentDateStr;
}

-(void)selected:(id)sender{
    UISegmentedControl* control = (UISegmentedControl*)sender;
    
    ip=[[segmentedArray objectAtIndex:control.selectedSegmentIndex] objectForKey:@"ip"];
    port=[[[segmentedArray objectAtIndex:control.selectedSegmentIndex] objectForKey:@"port"] intValue];
    NSLog(@"ip:%@,port:%d",ip,port);
}

/*
功能：监听内存警告
参数：无
返回值：无
 */
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
/*
功能：异常操作时弹出提示框
参数：msg 提示内容
返回值：无
 */
-(void)showMessage:(NSString *)msg{
    [imsiBtn setEnabled:YES];
    [smsBtn setEnabled:YES];
    [readICCID setEnabled:YES];
    [processBar stopAnimating];
    [getDeviceInfoBtn setEnabled:YES];
    [[[UIAlertView alloc] initWithTitle:@"结果" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
}
/*
功能：判断各个属性的值是否正常
参数：无
返回值：无
 */
-(void)readId{
    if(readerName.text==nil || [readerName.text isEqualToString:@""]){
        [self showMessage:@"请选择读头"];
        [self updateFinishUI];
        return;
    }
    beginTime.text=[self getNowTime];
    
    recrodTime = [[NSDate date] timeIntervalSince1970];
    
    
    NSLog(@"My App open reader start");
    //蓝牙名称为空时弹出提示框
    if([readerName.text isEqualToString:@""]){
        [[[UIAlertView alloc] initWithTitle:@"结果" message:@"请选择读头" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        [self performSelectorOnMainThread:@selector(updateFinishUI) withObject:nil waitUntilDone:NO];
        return;
    }
    if(deviceList.count>0){//查找设备
//        SRMyPeripheral *per=[[SRMyPeripheral alloc]init];
//        per.advName=readerName.text;
        if ([currentDevice isKindOfClass:[CBPeripheral class]]) {
            //通过setLisentPeripheral将蓝牙阅读器设置监听（相当连接读头），连接成功后，调用startScaleCard读取身份证，并等待结果回调
            if([idManager setLisentPeripheral:currentDevice withCBManager:manager]){   //该方法必须在子线程调用
                [idManager startScaleCard:30];
            }else{
                [[[UIAlertView alloc] initWithTitle:@"结果" message:@"阅读器监听失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                [self performSelectorOnMainThread:@selector(updateFinishUI) withObject:nil waitUntilDone:NO];
            }
        }else{
            if([idManager setLisentPeripheral:currentDevice]){  //该方法必须在子线程调用
                [idManager startScaleCard:30];
            }else{
                [[[UIAlertView alloc] initWithTitle:@"结果" message:@"阅读器监听失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                [self performSelectorOnMainThread:@selector(updateFinishUI) withObject:nil waitUntilDone:NO];
            }
        }
        
        
    }else{
        [[[UIAlertView alloc] initWithTitle:@"结果" message:@"未找到设备" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        [self performSelectorOnMainThread:@selector(updateFinishUI) withObject:nil waitUntilDone:NO];
    }
    
}
/*
功能：未找到设备时，停止刷新
参数：无
返回值：无
 */
-(void)updateFinishUI{
    
    NSLog(@"stop readid");
    [processBar stopAnimating];
    [stopBtn setEnabled:NO];
    [startBtn setEnabled:YES];
}
-(IBAction) start:(id)Sender
{//点击事件 读取二代身份证
    [self clearInfo];//读取身份证信息之前先清空信息
    [processBar startAnimating];
    [stopBtn setEnabled:YES];
    [startBtn setEnabled:NO];
    stop=false;
    readerState.text=@"开始读取身份证.......";
//    [self readId];
        [NSThread detachNewThreadSelector:@selector(readId) toTarget:self withObject:nil];
}

-(IBAction) stop:(id)sender
{//点击事件 停止读取
    NSLog(@"stop readid");
    stop=true;
    [processBar stopAnimating];
    [stopBtn setEnabled:NO];
    [startBtn setEnabled:YES];
}


- (IBAction)queryICCID:(id)sender {//点击事件 读取卡号
    
    [processBar startAnimating];
    [readICCID setEnabled:NO];
    [self readICCID];
//        [self performSelectorInBackground:@selector(readICCID) withObject:nil];
    
}

- (IBAction)showDeviceList:(id)sender {//点击事件 选择蓝牙名称列表
    
    //    [idManager stopRefreshDeviceList];
    
    deviceList = nil;
    manager.delegate = self;
    [manager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES}];
    [listView show];
//    [idManager refreshDeviceList];
//    [manager scanForPeripheralsWithServices:nil options:nil];
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        deviceList=[idManager getDeviceList:3];
//        NSLog(@"==========================%ld,%@",deviceList.count,deviceList);
//        [self performSelectorOnMainThread:@selector(refreshListView) withObject:nil waitUntilDone:NO];
//        //    NSLog(@"didUpdatePeripheralList:%@",deviceList);
//        
//    });
    
}

-(void)refreshListView{
    if(deviceList.count>0){
//        SRMyPeripheral *per=[deviceList objectAtIndex:0];
//        idManager=[SRIDCardReader instance];getDeviceList
//        [idManager setLisentPeripheral:per];
//        readerName.text=((SRMyPeripheral *)[peripherals objectAtIndex:0]).advName;
        rowCount=(int)deviceList.count;
        //        [listView reloadInputViews];
        
        [listView.mainPopoverListView reloadData];
    }
    else{
        rowCount=0;
        readerName.text=@"";
    }
    
}

- (IBAction)writeSMS:(id)sender {//点击事件 写入短信中心号
    [processBar startAnimating];
    [smsBtn setEnabled:NO];
    [self performSelectorInBackground:@selector(insertSMS:) withObject:sms.text];
}

- (IBAction)writeIMSI:(id)sender {//点击事件 写卡
    [processBar startAnimating];
    [imsiBtn setEnabled:NO];
    //    [self performSelectorInBackground:@selector(insertIMSI:) withObject:imsi.text];
    //    [self performSelectorInBackground:@selector(insertCard) withObject:nil];
    [self insertCard];
}

- (IBAction)setServer:(id)sender {//点击事件 设置服务器地址
    if (customAlertView==nil) {
        customAlertView        = [[UIAlertView alloc] initWithTitle:@"自定义服务器地址" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil,nil];
    }
    [customAlertView setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
    
    UITextField *nameField = [customAlertView textFieldAtIndex:0];
    nameField.placeholder  = @"请输入解密服务IP地址";
    nameField.text =currentIP;
    
    UITextField *ipField  = [customAlertView textFieldAtIndex:1];
    [ipField setSecureTextEntry:NO];
    ipField.placeholder   = @"请输入解密服务端口号";
    ipField.text          = [NSString stringWithFormat:@"%d",currentPort];
    
    //    UITextField *portField  = [customAlertView textFieldAtIndex:2];
    //    [portField setSecureTextEntry:NO];
    //    portField.placeholder   = @"请输入一个端口号";
    //    portField.text          = [NSString stringWithFormat:@"%d",currentPort];
    
    [customAlertView show];
}

- (IBAction)getDeviceInfoAct:(id)sender {//点击事件 设备信息
    [getDeviceInfoBtn setEnabled:NO];
    //    [self performSelectorInBackground:@selector(getDeviceInfo) withObject:nil];
    [self getDeviceInfo];
}

/*
功能：返回设备信息
参数：无
返回值：无
 */
- (void)getDeviceInfo{
    
    SRMyPeripheral *per=[[SRMyPeripheral alloc]init];
    per.advName=readerName.text;
    [idManager setLisentPeripheral:per];
    SRDeviceInfo *info=[idManager getDeviceInfo];
    NSString *infoStr=[NSString stringWithFormat:@"id:%@\nfactoryNo:%@",info.Id,info.factoryNo];
    [self performSelectorOnMainThread:@selector(showMessage:) withObject:infoStr waitUntilDone:NO];
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == alertView.firstOtherButtonIndex) {
        currentIP = [alertView textFieldAtIndex:0].text;
        currentPort = [[alertView textFieldAtIndex:1].text intValue];
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docPath = [paths objectAtIndex:0];
        NSString *myFile = [docPath stringByAppendingPathComponent:@"my.ip"];
        //保存解密后台IP
        [currentIP writeToURL:myFile atomically:YES];
        
        myFile = [docPath stringByAppendingPathComponent:@"my.port"];
        //保存解密后台端口
        [[NSString stringWithFormat:@"%d",currentPort] writeToFile:myFile atomically:YES];
        
        [idManager setServerIP:currentIP andPort:currentPort];
        
//        if([currentIP hasPrefix:@"192"]){
//            [self.keBleTool connectServer:@"192.168.26.3" WithPort:7443];
//        }else if([currentIP hasPrefix:@"106"]){
//            [self.keBleTool connectServer:@"106.39.30.174" WithPort:7443];
//        }else{
//            [self.keBleTool connectServer:@"218.56.11.181" WithPort:7443];
//        }
    }
    
}


-(void)clearInfo{
    photoData=[[NSMutableData alloc] init];
    name.text=@"";
    sex.text=@"";
    mz.text=@"";
    year.text=@"";
    mon.text=@"";
    day.text=@"";
    addr.text=@"";
    idNo.text=@"";
    org.text=@"";
    expDate.text=@"";
    readerState.text=@"查找阅读器。。。";
    photoImageView.image=nil;
    beginTime.text=@"";
    endTime.text=@"";
    timeConsuming.text=@"";
}


#pragma mark Sunrise_BLE_STIDCardReaderDelegate
/*
 功能：代理方法，当扫描到周围的蓝牙设备时，通过该代理获得代表各个蓝牙设备的对象数组。
 参数：peripherals 蓝牙设备对象数组
 返回值: 无
 */
//- (void)didUpdatePeripheralList:(NSArray *)peripherals
//{
//    
//    deviceList=[NSArray arrayWithArray:peripherals];
//    
//    //    NSLog(@"didUpdatePeripheralList:%@",deviceList);
//    if(deviceList.count>0){
//        //        SRMyPeripheral *per=[deviceList objectAtIndex:0];
//        //        idManager=[SRIDCardReader instance];
//        //        [idManager setLisentPeripheral:per];
//        //        readerName.text=((SRMyPeripheral *)[peripherals objectAtIndex:0]).advName;
//        rowCount=(int)peripherals.count;
//        //        [listView reloadInputViews];
//        [listView.mainPopoverListView reloadData];
//    }
//    else{
//        rowCount=0;
//        readerName.text=@"";
//    }
//    
//}

/*
 功能：代理方法，读取身份证失败时可以通过这个代理方法获取失败的蓝牙对象和原因。
 参数：peripheral 代表蓝牙设备的对象
 error 描述失败的具体原因
 返回值：无
 */
- (void)SRfailedBack:(SRMyPeripheral *)peripheral withError:(NSError *)error
{
    endTime.text=[self getNowTime];
    NSLog(@"耗时:%f",([[NSDate date] timeIntervalSince1970]-recrodTime)*1000);
    timeConsuming.text=[NSString stringWithFormat:@"%.0f毫秒",([[NSDate date] timeIntervalSince1970]-recrodTime)*1000];
    NSLog(@"%@",error.description);
    switch(error.code)
    {
        case 0:
            readerState.text=@"请点击读二代证按钮";
            break;
        case -7:
            readerState.text=@"读取超时";
            break;
        case -4:
            readerState.text=@"检测不到二代证";
            break;
        case -9:
            readerState.text=@"连接后台失败";
            break;
        case -6:
            readerState.text=@"读头数据异常";
            break;
        case -5:
            readerState.text=@"网络传输超时";
            break;
        case -3:
            readerState.text=@"后台通信出错";
            break;
        case -2:
            readerState.text=@"无后台服务";
            break;
        case -1:
            readerState.text=@"连接读头失败";
            break;
        case -10:
            readerState.text=@"未设置IP";
            break;
        default:
            readerState.text=@"未知错误";
            break;
            
    }
    [self updateFinishUI];
}
/*
 功能： 代理方法，读取身份证成功时可以通过这个代理方法获取身份证的文本信息和照片信息。
 参数：peripheral代表蓝牙设备的对象
 data 如果data是NSDictionary类型，则里面包含的信息是文本信息，具体获取各字段信息见下表；如果data是NSData类型，则里面包含的是照片的二进制数据流
 返回值：无
 */
- (void)SRsuccessBack:(SRMyPeripheral *)peripheral withData:(id)data
{
    endTime.text=[self getNowTime];
    NSLog(@"耗时:%f",([[NSDate date] timeIntervalSince1970]-recrodTime)*1000);
    timeConsuming.text=[NSString stringWithFormat:@"%.0f毫秒",([[NSDate date] timeIntervalSince1970]-recrodTime)*1000];
    if([data isKindOfClass:[NSDictionary class]]){
        NSDictionary *idInfo=(NSDictionary *)data;
        //        NSLog(@"%@",[data objectForKey:@"Name"]);
        //        [self performSelectorOnMainThread:@selector(showMessage:) withObject:[data objectForKey:@"Name"] waitUntilDone:NO];
        name.text=[idInfo objectForKey:@"Name"];
        sex.text=[idInfo objectForKey:@"Sex"];
        year.text=[[idInfo objectForKey:@"Born"] substringWithRange:NSMakeRange(0, 4)];
        mon.text=[[idInfo objectForKey:@"Born"] substringWithRange:NSMakeRange(4, 2)];
        day.text=[[idInfo objectForKey:@"Born"] substringWithRange:NSMakeRange(6, 2)];
        mz.text=[idInfo objectForKey:@"Nation"];
        addr.text=[idInfo objectForKey:@"Address"];
        idNo.text=[idInfo objectForKey:@"CardNo"];
        org.text=[idInfo objectForKey:@"IssuedAt"];
        expDate.text=[NSString stringWithFormat:@"%@-%@",(NSString *)[idInfo objectForKey:@"EffectedDate"],(NSString *)[idInfo objectForKey:@"ExpiredDate"]];
        NSLog(@"DN:%@",[idInfo objectForKey:@"Dn"]);
        dn.text=[idInfo objectForKey:@"Dn"];
        
    }else{
        NSLog(@"%lu",(unsigned long)[data length]);
        [photoData appendData:data];
        UIImage* image=[UIImage imageWithData:photoData scale:1.0];
        NSLog(@"size:%f %f",image.size.width,image.size.height);
        ((UIImageView*)photoImageView).image=image;
        [photoImageView setNeedsDisplay];
        readerState.text=@"读取成功！";
        [self updateFinishUI];
    }
}

/*
 功能:代理方法,读取卡号时通过该方法返回结果
 参数:结果信息
 返回值:无
 */
- (void)ReadICCIDsuccessBack:(SRIDReadCardInfo*)peripheral withData:(id)data{
    NSLog(@"%d",[((NSNumber *)data) intValue]);
    [self performSelectorOnMainThread:@selector(showMessage:) withObject:[NSString stringWithFormat:@"%@:%@",data,peripheral.ICCID] waitUntilDone:NO];
}

/*
 功能:代理方法,写卡时通过该方法返回结果
 参数:结果信息
 返回值:无
 */
- (void)writeCardResultBack:(SRIDReadCardInfo*)peripheral withData:(id)data{
    [self performSelectorOnMainThread:@selector(showMessage:) withObject:peripheral.writeCardResult==0?@"成功":@"失败" waitUntilDone:NO];
}

/*
 功能：返回读取结果的JSON字符串
 参数：JSON字符串
 返回值：无
 */
- (void)idCardInfoJsonStr:(NSString *)jsonStr{
    readerState.text=@"读取成功！";
    [self updateFinishUI];
    [self showMessage:jsonStr];
}
/*
功能：读取ICCID信息
参数：无
返回值：无
 */
-(void)readICCID{
//    SRMyPeripheral *per=[[SRMyPeripheral alloc]init];
//    per.advName=readerName.text;
//    [idManager setLisentPeripheral:per];
//    NSString *iccid=[[NSString alloc] init];
//    SRIDReadCardInfo *info=[idManager readCardInfo:@"2"];
//    [self showMessage:[NSString stringWithFormat:@"%@:%@",info.retCode,info.ICCID]];
    if([idManager setLisentPeripheral:currentDevice withCBManager:manager]){
        [idManager readSimICCID:@""];
//        SRIDReadCardInfo *result=[idManager readCardInfo:@"2"];
//        [self showMessage:result.ICCID];
//        NSLog(@"%@",result.ICCID);
    }else{
        [self showMessage:@"阅读器监听失败"];
    }
    
    
    //测试启动另一个应用
    //    NSURL * myURL_APP_A = [NSURL URLWithString:@"esaleb://skgjjsdjgiowjeig?key=sdg&id=sss"];
    //    if ([[UIApplication sharedApplication] canOpenURL:myURL_APP_A]) {
    //        NSLog(@"canOpenURL");
    //        [[UIApplication sharedApplication] openURL:myURL_APP_A];
    //    }
}

-(void)insertCard{
    SRMyPeripheral *per=[[SRMyPeripheral alloc]init];
    per.advName=readerName.text;
    [idManager setLisentPeripheral:per];
    [idManager writeSimCard:imsi.text withNo:sms.text];
//    [idManager insertCard:@"!A0A40000023F00,S,,9FXX!A0A40000027F10,S,,9FXX!A0A40000026F42,S,,9FXX!A0DC010428FFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF0891683110808805F0FFFFFFFFFFFF,S,,9000"
//                    iccid:@"89860115897037579358"
//                     imsi:@"460015226691752" number:@"18665224379"];
    
}

-(void)insertIMSI:(NSString *)imisStr{
    SRMyPeripheral *per=[[SRMyPeripheral alloc]init];
    per.advName=readerName.text;
    [idManager setLisentPeripheral:per];
    int info=[idManager writeIMSI:imisStr];
    [self performSelectorOnMainThread:@selector(showMessage:) withObject:[NSString stringWithFormat:@"%d",info] waitUntilDone:NO];
}
/*
   功能：编写SMS号
   参数：SMS字符串
   返回值：无
 */
-(void)insertSMS:(NSString *)smsStr{
    SRMyPeripheral *per=[[SRMyPeripheral alloc]init];
    per.advName=readerName.text;
    [idManager setLisentPeripheral:per];
    int info=[idManager writeMSGNumber:smsStr number:0x01];
    [self performSelectorOnMainThread:@selector(showMessage:) withObject:[NSString stringWithFormat:@"%d",info] waitUntilDone:NO];
}


#pragma mark -ZSYPopoverListView
- (NSInteger)popoverListView:(ZSYPopoverListView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return rowCount;
}

- (UITableViewCell *)popoverListView:(ZSYPopoverListView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *identifier = @"identifier";
    UITableViewCell *cell = [tableView dequeueReusablePopoverCellWithIdentifier:identifier];
    if (nil == cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if ( self.selectedIndexPath && NSOrderedSame == [self.selectedIndexPath compare:indexPath])
    {
        cell.imageView.image = [UIImage imageNamed:@"fs_main_login_selected.png"];
    }
    else
    {
        cell.imageView.image = [UIImage imageNamed:@"fs_main_login_normal.png"];
    }
    @try {
        cell.textLabel.text = ((CBPeripheral *)[deviceList objectAtIndex:indexPath.row]).name;
    } @catch (NSException *exception) {
        cell.textLabel.text = ((SRMyPeripheral *)[deviceList objectAtIndex:indexPath.row]).advName;
    } @finally {
        
    }
    
    return cell;
}

- (void)popoverListView:(ZSYPopoverListView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView popoverCellForRowAtIndexPath:indexPath];
    cell.imageView.image = [UIImage imageNamed:@"fs_main_login_normal.png"];
    NSLog(@"deselect:%d", (int)indexPath.row);
}

- (void)popoverListView:(ZSYPopoverListView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedIndexPath = indexPath;
    UITableViewCell *cell = [tableView popoverCellForRowAtIndexPath:indexPath];
    cell.imageView.image = [UIImage imageNamed:@"fs_main_login_selected.png"];
    NSLog(@"select:%d", (int)indexPath.row);
    readerName.text=cell.textLabel.text;
    currentDevice=[deviceList objectAtIndex:indexPath.row];
    
    [self performSelectorOnMainThread:@selector(listDismiss) withObject:nil waitUntilDone:NO];
}

-(void)listDismiss{
    [listView dismiss];
}


#pragma  mark -- CBCentralManagerDelegate

- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
            //判断状态开始扫瞄周围设备 第一个参数为空则会扫瞄所有的可连接设备  你可以
            //指定一个CBUUID对象 从而只扫瞄注册用指定服务的设备
            //scanForPeripheralsWithServices方法调用完后会调用代理CBCentralManagerDelegate的
            //- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI方法
        case CBCentralManagerStatePoweredOn:
            [manager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES}];
            
            break;
        case CBCentralManagerStatePoweredOff:
            [self showMessage:@"尚未打开蓝牙，请在设置中打开"];
            break;
            
        default:
            break;
    }
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheraln advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    //发现设备
//    if([peripheraln.name isEqualToString:@"SR52015A100000"]){
//        BOOL ret=[idManager openReader:peripheraln withCBManager:manager];
//        NSLog(@"connect:%@",ret?@"true":@"false");
//    }
    //发现设备
    //    if([peripheraln.name hasPrefix:@"SPPLE" ] || [peripheraln.name hasPrefix:@"KT"]){
    
//    NSString *devname=[advertisementData valueForKey:@"kCBAdvDataLocalName"];
//    if(devname.length==0){
//        devname=peripheraln.name;
//    }
//    
    if(deviceList==nil){
        deviceList=[NSMutableArray array];
    }
    NSLog(@"peripheraln:%@",peripheraln);
    if([deviceList containsObject:peripheraln]){
        return;
    }
    
    [deviceList addObject:peripheraln];
    NSLog(@"%@",deviceList);
    rowCount=[deviceList count];
    [listView.mainPopoverListView reloadData];
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    NSLog(@"has connected");
//    [self.mutableData setLength:0];
//    self.peripheral.delegate = self;
    //此时设备已经连接上了  你要做的就是找到该设备上的指定服务 调用完该方法后会调用代理CBPeripheralDelegate（现在开始调用另一个代理的方法了）的
    //- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
//    [self.peripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];
    
}


- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    //此时连接发生错误
    NSLog(@"connected periphheral failed");
}


#pragma mark -- CBPeripheralDelegate
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    if (error==nil) {
        //在这个方法中我们要查找到我们需要的服务  然后调用discoverCharacteristics方法查找我们需要的特性
        //该discoverCharacteristics方法调用完后会调用代理CBPeripheralDelegate的
        //- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
        for (CBService *service in peripheral.services) {
            if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
                [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:kCharacteristicUUID]] forService:service];
            }
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    if (error==nil) {
        //在这个方法中我们要找到我们所需的服务的特性 然后调用setNotifyValue方法告知我们要监测这个服务特性的状态变化
        //当setNotifyValue方法调用后调用代理CBPeripheralDelegate的- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
        for (CBCharacteristic *characteristic in service.characteristics) {
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {
                
                [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            }
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    if (error==nil) {
        //调用下面的方法后 会调用到代理的- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
        [peripheral readValueForCharacteristic:characteristic];
    }
}


- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    
}

-(BOOL)parser:(NSString*)string
{
    //系统自带的
    NSXMLParser *par = [[NSXMLParser alloc] initWithData:[string dataUsingEncoding:NSUTF8StringEncoding]];
    [par setDelegate:self];//设置NSXMLParser对象的解析方法代理
    return [par parse];//调用代理解析NSXMLParser对象，看解析是否成功
    
}

#pragma mark xmlparser
//step 1 :准备解析
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    //    NSLog(@"%@",NSStringFromSelector(_cmd) );
    
    
}
//step 2：准备解析节点
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    NSLog(@"%@",elementName);
    if([elementName isEqualToString:@"partyName"]){
        certInfoKey=@"Name";
    }else if([elementName isEqualToString:@"bornDay"]){
        certInfoKey=@"Born";
    }else if([elementName isEqualToString:@"certOrg"]){
        certInfoKey=@"IssuedAt";
    }else if([elementName isEqualToString:@"certNumber"]){
        certInfoKey=@"CardNo";
    }else if([elementName isEqualToString:@"expDate"]){
        certInfoKey=@"ExpiredDate";
    }else if([elementName isEqualToString:@"identityPic"]){
        certInfoKey=@"identityPic";
    }else if([elementName isEqualToString:@"certAddress"]){
        certInfoKey=@"Address";
    }else if([elementName isEqualToString:@"effDate"]){
        certInfoKey=@"EffectedDate";
    }else if([elementName isEqualToString:@"gender"]){
        certInfoKey=@"Sex";
    }else if([elementName isEqualToString:@"nation"]){
        certInfoKey=@"Nation";
    }else {
        certInfoKey=@"other";
    }
}

//step 3:获取首尾节点间内容
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    NSLog(@"%@,%@",certInfoKey,string);
    if([certInfoKey isEqualToString:@"identityPic"]){
        [self SRsuccessBack:nil withData:[[NSData alloc] init]];
        return;
    }
    if((string!=nil) & ![string isEqualToString:@""] & [certInfo objectForKey:certInfoKey]==nil)
        [certInfo setValue:string forKey:certInfoKey];
    NSLog(@"%@",NSStringFromSelector(_cmd) );
}

//step 4 ：解析完当前节点
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    NSLog(@"%@",NSStringFromSelector(_cmd) );
}

//step 5；解析结束
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    //    NSLog(@"%@",NSStringFromSelector(_cmd) );
    [self SRsuccessBack:nil withData:certInfo];
}
//获取cdata块数据
- (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
    //    NSLog(@"%@",NSStringFromSelector(_cmd) );
}

#pragma KaEr代理
//设置需要相片解码接口后需要实现委托方法
-(void)BR_DecodedCardPic:(NSData*)picData{
    [photoData appendData:picData];
    UIImage* image=[UIImage imageWithData:photoData scale:1.0];
    NSLog(@"size:%f %f",image.size.width,image.size.height);
    ((UIImageView*)photoImageView).image=image;
    [photoImageView setNeedsDisplay];
}

@end
